/* eslint-disable @typescript-eslint/indent */
import { computed, Ref, ref } from 'vue';
import { UseResizeHandle } from './types';

export function useResizeHandle(
    splitterElementRef: Ref<HTMLElement | undefined>
): UseResizeHandle {
    const horizontalResizeBarPosition = ref(-1);
    const verticalResizeBarPosition = ref(-1);
    const horizontalResizeHandleOffset = ref(0);
    const verticalResizeHandleOffset = ref(0);
    const showHorizontalResizeHandle = ref(false);
    const showVerticalResizeHandle = ref(false);

    const horizontalResizeHandleStyle = computed(() => {
        const styleObject = {
            display: showHorizontalResizeHandle.value ? 'block' : 'none',
            left: `${horizontalResizeHandleOffset.value}px`
        } as Record<string, any>;
        return styleObject;
    });

    const verticalResizeHandleStyle = computed(() => {
        const styleObject = {
            display: showVerticalResizeHandle.value ? 'block' : 'none',
            top: `${verticalResizeHandleOffset.value}px`
        } as Record<string, any>;
        return styleObject;
    });

    const resizeOverlayStyle = computed(() => {
        const styleObject = {
            display: (showVerticalResizeHandle.value || showHorizontalResizeHandle.value) ? 'block' : 'none'
        } as Record<string, any>;
        return styleObject;
    });

    function draggingHorizontalResizeHandle($event: MouseEvent) {
        const splitterElement = splitterElementRef.value;
        if (splitterElement) {
            const { left: splitterOffsetLeft } = (splitterElement.getBoundingClientRect() as DOMRect);
            horizontalResizeHandleOffset.value = $event.clientX - splitterOffsetLeft;
        }
    }

    function draggingVerticalResizeHandle($event: MouseEvent) {
        const splitterElement = splitterElementRef.value;
        if (splitterElement) {
            const { top: splitterOffsetTop } = (splitterElement.getBoundingClientRect() as DOMRect);
            verticalResizeHandleOffset.value = $event.clientY - splitterOffsetTop;
        }
    }

    return {
        horizontalResizeHandleStyle,
        verticalResizeHandleStyle,
        resizeOverlayStyle,
        showHorizontalResizeHandle,
        showVerticalResizeHandle,
        horizontalResizeBarPosition,
        verticalResizeBarPosition,
        verticalResizeHandleOffset,
        horizontalResizeHandleOffset,
        draggingHorizontalResizeHandle,
        draggingVerticalResizeHandle
    };
}
